package org.hyy.action;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hyy.dao.PayDAO;
import org.hyy.vo.Pay;

import com.alipay.services.AlipayService;
import com.tenpay.PayRequestHandler;
import com.tenpay.TenPayConfig;
import com.tenpay.util.TenpayUtil;

/**
 * 订单相关
 * 
 * @author yuanyuan.han
 * 
 */
public class PayAction extends BasicAction {
	private static final long serialVersionUID = 8248020579218204706L;
	private List<Pay> payList;

	public List<Pay> getPayList() {
		return payList;
	}

	public String buyProduct() {
		HttpServletRequest request = getRequest();
		String pid = request.getParameter("pid");
		String money = request.getParameter("money");
		if (getUser() == null) {
			return "gologin";
		} else {
			PayDAO payDAO = new PayDAO();
			getResponse().setContentType("text/html; charset=UTF-8");
			getResponse().setCharacterEncoding("UTF-8");
			String orderKey = "";
			Pay pay = new Pay();
			pay.setName(getUser());
			pay.setProid(pid);
			pay.setMemberPrice(Double.valueOf(money));
			pay.setPdate(new Date());
			orderKey = payDAO.insertOne(pay);
			try {
				out(tenpay(orderKey, money));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	private String tenpay(String orderKey, String money) throws UnsupportedEncodingException {
		HttpServletRequest request = getRequest();
		HttpServletResponse response = getResponse();
		
		//商户号
		String bargainor_id = TenPayConfig.bargainor_id;

		//密钥
		String key = TenPayConfig.key;

		//回调通知URL
		String return_url = TenPayConfig.return_url;

		//当前时间 yyyyMMddHHmmss
		String currTime = TenpayUtil.getCurrTime();

		//8位日期
		String strDate = currTime.substring(0, 8);

		//6位时间
		String strTime = currTime.substring(8, currTime.length());

		//四位随机数
		String strRandom = TenpayUtil.buildRandom(4) + "";

		//10位序列号,可以自行调整。
		String strReq = strTime + strRandom;

		//商家订单号,长度若超过32位，取前32位。财付通只记录商家订单号，不保证唯一。
		String sp_billno = orderKey;

		//财付通交易单号，规则为：10位商户号+8位时间（YYYYmmdd)+10位流水号
		String transaction_id = bargainor_id + strDate + strReq;

		//创建PayRequestHandler实例
		PayRequestHandler reqHandler = new PayRequestHandler(request, response);

		//设置密钥
		reqHandler.setKey(key);

		//初始化
		reqHandler.init();

		//钱数 以分为单位
		BigDecimal totalMoney = new BigDecimal(money);
		BigDecimal aa = new BigDecimal(100);
		//-----------------------------
		//设置支付参数
		//-----------------------------
		reqHandler.setParameter("bargainor_id", bargainor_id);			//商户号
		reqHandler.setParameter("sp_billno", sp_billno);				//商家订单号
		reqHandler.setParameter("transaction_id", transaction_id);		//财付通交易单号
		reqHandler.setParameter("return_url", return_url);				//支付通知url
		reqHandler.setParameter("desc", "公司账户充值：" + transaction_id);	    //商品名称
		reqHandler.setParameter("total_fee", String.valueOf(totalMoney.multiply(aa).setScale(0)));	//商品金额,以分为单位

		//用户ip,测试环境时不要加这个ip参数，正式环境再加此参数
		reqHandler.setParameter("spbill_create_ip",request.getRemoteAddr());

		//获取请求带参数的url
		String requestUrl = reqHandler.getRequestForm();
		
		return requestUrl;
	}
	
	private String alipay(String orderKey, String money) {
		String subject = "简单商城系统订单";
		String remark = "购买商品";
		// 默认支付方式，取值见“即时到帐接口”技术文档中的请求参数列表
		String paymethod = "";
		// 默认网银代号，代号列表见“即时到帐接口”技术文档“附录”→“银行列表”
		String defaultbank = "";

		// 扩展功能参数——防钓鱼//

		// 防钓鱼时间戳
		String anti_phishing_key = "";
		// 获取客户端的IP地址，建议：编写获取客户端IP地址的程序
		String exter_invoke_ip = "";
		// 自定义参数，可存放任何内容（除=、&等特殊字符外），不会显示在页面上
		String extra_common_param = "";
		// 默认买家支付宝账号
		String buyer_email = "";
		// 商品展示地址，要用http:// 格式的完整路径，不允许加?id=123这类自定义参数
		String show_url = "http://www.xxx.com/order/myorder.jsp";

		// 扩展功能参数——分润(若要使用，请按照注释要求的格式赋值)//

		// 提成类型，该值为固定值：10，不需要修改
		String royalty_type = "";
		// 提成信息集
		String royalty_parameters = "";
		Map<String, String> sParaTemp = new HashMap<String, String>();
		sParaTemp.put("payment_type", "1");
		sParaTemp.put("out_trade_no", orderKey);
		sParaTemp.put("subject", subject);
		sParaTemp.put("body", remark);
		sParaTemp.put("total_fee", money);
		sParaTemp.put("show_url", show_url);
		sParaTemp.put("paymethod", paymethod);
		sParaTemp.put("defaultbank", defaultbank);
		sParaTemp.put("anti_phishing_key", anti_phishing_key);
		sParaTemp.put("exter_invoke_ip", exter_invoke_ip);
		sParaTemp.put("extra_common_param", extra_common_param);
		sParaTemp.put("buyer_email", buyer_email);
		sParaTemp.put("royalty_type", royalty_type);
		sParaTemp.put("royalty_parameters", royalty_parameters);

		// 构造函数，生成请求URL
		String sHtmlText = AlipayService.create_direct_pay_by_user(sParaTemp);
		return sHtmlText;
	}
	
	public String deletePay(){
		HttpServletRequest request = getRequest();
		String pid = request.getParameter("pid");
		PayDAO payDAO = new PayDAO();
		payDAO.delete(Integer.valueOf(pid));
		return "showpay";
	}
	
	public String deletemyPay(){
		HttpServletRequest request = getRequest();
		String pid = request.getParameter("pid");
		PayDAO payDAO = new PayDAO();
		payDAO.delete(Integer.valueOf(pid));
		return "showpay";
	}
	
	public String myPay(){
		payList = new ArrayList<Pay>();
		PayDAO payDAO = new PayDAO();
		payList = payDAO.showallByUsername((String)session.get("user"));
		return "showpay";
	}
}
